package com.example.dell.jakatra.rxjava;

import android.content.Context;
import android.net.ParseException;

import com.example.dell.jakatra.retrofit.BaseAbsResponse;
import com.example.dell.jakatra.util.NetUtil;
import com.example.dell.jakatra.util.ToastUtil;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by johnvi on 2017/3/10
 * mail:229200348@qq.com
 */

public abstract class BaseSubscriber<T> extends Subscriber<BaseAbsResponse<T>> {
    private static final String TAG = BaseSubscriber.class.getSimpleName();

    protected Context mBsContext;
    protected boolean isShowErrToast = true;



    @Override
    public void onStart() {
        checkIsNetWorkAvailable();
        showLoadView();
    }


    private void checkIsNetWorkAvailable() {
        if (!NetUtil.isNetworkAvailable()) {
            unBaseSubscribe();
            if (mBsContext == null) {
                return;
            }
            ToastUtil.show("网络异常,稍后再试!");
        }
        onCompleted();
    }

    protected void unBaseSubscribe() {
        if (!isUnsubscribed()) {
            unsubscribe();
            misLoadView();
        }
    }


    @Override
    public void onCompleted() {
        misLoadView();
        onFinish();
    }


    private void showLoadView() {

    }


    private void misLoadView() {

    }

    @Override
    public void onNext(BaseAbsResponse<T> tBaseAbsResponse) {
        onSuccess(tBaseAbsResponse.getData());
    }

    @Override
    public void onError(Throwable e) {
        misLoadView();
        onErr(e);

        if (e instanceof SocketTimeoutException
                || e instanceof ConnectException
                || e instanceof HttpException) {
            onEmpty();
            if (isShowErrToast) {
                ToastUtil.show("您的网络开小差了");
            }
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {

        } else {
        }


    }


    public void onEmpty() {

    }


    public abstract void onFinish();

    public abstract void onErr(Throwable e);

    public abstract void onSuccess(T t);

}
